import jsList from "../js";
import {
  setSessionItem,
  getSessionItem,
  // removeSessionItem,
  // ishasAgentId
  formatNumber
} from "@/basa/utils";
import {
  listPageMoveInventory,
  removeMoveInventory,
  recallMoveInventory
} from "../api";

export default {
  data() {
    return {
      jsList,
      focuses: [{ focus: 0 }, { focus: 1 }, { focus: 2 }, { focus: 3 }],
      isActive: 0,
      // search
      formData: {
        moveInventoryName: "", //移库单名称
        moveInventoryCode: "", //移库单编号
        reportInOrgName: "", //填报单位
        originalWarehouseName: "", //原仓库
        targetWarehouseName: "", //目标仓库
        billStatus: "", //单据状态
        reportTime: "" //编制日期
      },
      formDataSearch: {},
      localSearchData: {},
      // 单据状态
      moveStoreList: {
        2: "待提交",
        4: "已撤回",
        3: "审批中",
        6: "审批退回",
        5: "审批通过"
      },
      tableData: [],
      totalNum: 0,
      pageNoCode: 1,
      pageSizeCode: 10,
      formatterList: {
        // 移库数量
        moveInventoryCount(row) {
          return formatNumber(Number(row.moveInventoryCount), 3);
        },
        // 移库金额
        moveInventoryMoney(row) {
          return Number(row.moveInventoryMoney).toFixed(2);
        },
        reportTime(row) {
          return row.reportTime ? row.reportTime.substring(0, 10) : "";
        },
        isAcrossProject(row){
            let str = { 0: "否", 1: "是" };
            let isAcross = [0, 1].includes(
              row.isAcrossProject
            )
              ? str[row.isAcrossProject]
              : "";
              return isAcross;
        }
      },
      recordsTotal: "",
    };
  },
  methods: {
    // 清空名称空格
    handleTrim(key) {
      this.$set(
        this.formData,
        key,
        this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    },
    search(searchData) {
      this.pageNoCode = 1;
      if (searchData.reportTime && searchData.reportTime.length) {
        searchData.reportTimeStart = new Date(
          searchData.reportTime[0].replace(/-/g, "/")
        ).getTime();
        searchData.reportTimeEnd = new Date(
          searchData.reportTime[1].replace(/-/g, "/")
        ).getTime();
        delete searchData.reportTime;
      }
      this.formDataSearch = JSON.parse(JSON.stringify(searchData));
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      this.getList(this.formDataSearch);
    },
    change(index, key, value) {
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map(_ => {
        if (_ !== key) this.formData[_] = "";
      });
    },
    tabChange(type) {
      switch (type) {
        case 0:
          this.$router.push("/inventoryManagement/move-store/list");
          break;
        case 1:
          this.$router.push("/inventoryManagement/move-store/unSubmit");
          break;
        case 2:
          this.$router.push("/inventoryManagement/move-store/approved");
          break;
        case 3:
          this.$router.push("/inventoryManagement/move-store/return");
          break;
      }
    },
    getList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pageSizeCode;
      obj.labelType = "1";
      // obj.isShowPageLoading = true;
      obj.labelType = this.isActive;
      if (obj.billStatus == "待提交") {
        obj.billStatus = "2";
      } else if (obj.billStatus == "已撤回") {
        obj.billStatus = "4";
      } else if (obj.billStatus == "审批中") {
        obj.billStatus = "3";
      } else if (obj.billStatus == "审批退回") {
        obj.billStatus = "6";
      } else if (obj.billStatus == "审批通过") {
        obj.billStatus = "5";
      } else if (obj.billStatus == "冲销中") {
        obj.billStatus = "21";
      } else if (obj.billStatus == "已冲销") {
        obj.billStatus = "22";
      }
      console.log(obj);
      listPageMoveInventory(obj).then(res => {
        console.log(res);
        this.tableData = res.data.data.rows;
        this.tableData.forEach((item, index) => {
          item.billStatus = this.moveStoreList[item.billStatus];
        });
        // this.totalNum = res.data.data.total;
        this.totalNum = res.data.data.recordsTotal;
      });
    },
    // 上一页
    handlePrev() {
      --this.pageNoCode;
      this.getList();
    },
    // 下一页
    handleNext() {
      ++this.pageNoCode;
      this.getList();
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList(this.formDataSearch);
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      setSessionItem("pageNo", this.tableName, {
        pageNo: val,
        searchForm: searchFormData.searchForm || {}
      });
      this.formDataSearch = {
        ...this.formDataSearch,
        ...searchFormData.searchForm
      };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      this.getList(this.formDataSearch);
    },
    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = this.jsList.unfixedTableThead.concat(
        this.jsList.fixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, width, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          this.jsList.unfixedTableThead = localTableData.filter(item => {
            return !this.jsList.fixedTableThead.find(
              cItem => item.prop === cItem.prop
            );
          });
        } else {
          // 长度相同但值不同
          this.tableThead = this.jsList.unfixedTableThead.concat(
            this.jsList.fixedTableThead
          );
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = this.jsList.unfixedTableThead.concat(
          this.jsList.fixedTableThead
        );
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.jsList.unfixedTableThead.length; i++) {
        if (this.jsList.unfixedTableThead[i].label === column.label) {
          this.jsList.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.jsList.unfixedTableThead.concat(
        this.jsList.fixedTableThead
      );
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.draggFlag = false;
      this.$nextTick(() => {
        this.draggFlag = true;
      });
    },
    goAdd() {
      this.$router.push("/inventoryManagement/move-store/add");
    },
    // 编辑
    goEdit(row) {
      this.$router.push({
        path: "/inventoryManagement/move-store/edit",
        query: {
          name: row.moveInventoryName,
          id: row.id
        }
      });
    },
    // 删除
    goDelete(row) {
      this.$confirm("您确定要删除吗？", "删除确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      })
        .then(() => {
          removeMoveInventory({
            id: row.id,
            isShowLoading: true,
            loadingMessage: "删除中,请稍等..."
          }).then(res => {
            if (res.data.code === "0") {
              this.$message({
                type: "success",
                message: res.data.message,
                showClose: true,
                ccuiCustom: true,
                duration: 8000
              });
              this.getList();
            }
          });
        })
        .catch(() => {});
    },
    // 撤回
    goRecall(row) {
      this.$confirm("您确定要撤回吗？", "撤回确认", {
        distinguishCancelAndClose: true,
        confirmButtonText: "撤回",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      })
        .then(() => {
          recallMoveInventory({
            id: row.id,
            isShowLoading: true,
            loadingMessage: "撤回中,请稍等..."
          }).then(res => {
            if (res.data.code === "0") {
              this.$message({
                type: "success",
                message: res.data.message,
                showClose: true,
                ccuiCustom: true,
                duration: 8000
              });
              this.getList();
            }
          });
        })
        .catch(() => {});
    },
    cellClick(row, column) {
      if (column.label === "移库单编号") {
        this.$router.push({
          path: "/inventoryManagement/move-store/detail",
          query: {
            name: row.moveInventoryName,
            id: row.id,
            states: "move-store"
          }
        });
      }
    }
  },
  activated() {
    this.getList(this.formDataSearch);
  },
  created() {
    this.getList(this.formDataSearch);
  }
};
